package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RequestMapping("/common")
@RestController
public class CommonController {


    @Value("${reggie.upload_path}")
    private String uploadPath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        try {
            //0.获取上传文件的名称  aa.jpg
            String originalFilename = file.getOriginalFilename();

            //优化1：使用UUID为上传成功的文件重新命名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); //文件后缀
            String fileName = UUID.randomUUID().toString()+suffix;

            //优化2：将服务器保存上传文件路径设置到配置文件中
            //1.设置服务器上传文件路径      直接从配置文件中获取设置的文件上传保存路径
            //String uploadPath = "D:\\reggie\\";

            //优化3：判断文件上传保存路径是否存在 不存在就创建
            File uploadDirectory = new File(uploadPath);
            if(!uploadDirectory.exists()){
                uploadDirectory.mkdirs();
            }

            //2.将上传的文件保存到服务器指定位置
            File uploadFile = new File(uploadPath+fileName);
            file.transferTo(uploadFile);

            //3.响应文件上传成功
            return R.success(fileName);

        } catch (IOException e) {
            //e.printStackTrace();
            throw new CustomException(e.getMessage());
        }
    }


    /**
     * 文件下载
     * @param name
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //1.判断要下载的文件名称是否为null|""  是:不要
        if(StringUtils.isEmpty(name)){
            throw new CustomException("文件名称为空，不能下载！");
        }

        //2.根据要下载的文件名称和服务器保存的文件路径找到真实要下载的文件
        //获取要下载的文件的字节输入流
        InputStream is = new FileInputStream(uploadPath+name);

        //3.使用IO读写 将文件写给客户端浏览器
        ServletOutputStream os = response.getOutputStream();
        byte[] b = new byte[8192];
        int len = -1;
        while((len=is.read(b))!=-1){
            os.write(b,0,len);
        }

        //4.关闭流
        os.close();
        is.close();
    }
}
